package holiday

import (
	"net/http"
	"strings"
	"time"

	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/config"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"github.com/gin-gonic/gin"
)

type holidayResult struct { //列表查询输出
	Date      string
	IsHoliday bool
}

// 启动定时监测任务
func IsHoliday(c *gin.Context) {

	dateStr := c.DefaultPostForm("dateList", "")
	if dateStr == "" {
		global.Log.Error("IsHoliday date string is none.")
		c.JSON(http.StatusOK, model.Fail("无查询日期"))
		return
	}

	dateList := strings.Split(dateStr, ",")
	if len(dateList) <= 0 {
		global.Log.Error("IsHoliday date array is none.")
		c.JSON(http.StatusOK, model.Fail("日期数组为空"))
		return
	}

	output := []*holidayResult{}
	for _, date := range dateList {
		source := date
		result := &holidayResult{
			Date:      source,
			IsHoliday: false,
		}
		if CheckHoliday(date) {
			result.IsHoliday = true
		} else {
			result.IsHoliday = false
		}
		output = append(output, result)
	}

	c.JSON(http.StatusOK, model.SuccessObject("success", output))
	return

}

func CheckHoliday(date string) bool {
	if strings.Contains(date, "-") { //yyyy-mm-dd格式，调整为yyyymmdd
		date = strings.Replace(date, "-", "", -1)
	}
	if strings.Contains(date, "/") { //yyyy/mm/dd格式，调整为yyyymmdd
		date = strings.Replace(date, "/", "", -1)
	}
	holidayString := config.Holiday().HolidayString
	if strings.Contains(holidayString, date) {
		return true
	}
	d, err := time.Parse("20060102", date)
	if err != nil { //日期非法
		return false
	}
	if d.Weekday() == time.Sunday || d.Weekday() == time.Saturday {
		return true
	}
	return false
}

func IsWorkDay(date time.Time) bool {
	if date.Weekday() == time.Sunday || date.Weekday() == time.Saturday {
		return false
	}
	holidayString := config.Holiday().HolidayString
	d := date.Format("20060102")
	if strings.Contains(holidayString, d) {
		return false
	}
	return true
}
